<template>
  <div class="centermap">
    <div class="maptitle">
    </div>

    <div class="mapwrap">
      <div id="map" style="width: 100%; height: 100%;" class="my-bd-map"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, nextTick, reactive} from 'vue'
import {ref} from 'vue';
import {getMapPoints, getMapCenter} from "@/api";
import {ElMessage} from "element-plus";

// 声明百度地图相关类型（简化版）
interface BMapGLPoint {
  lng: number
  lat: number
}

interface BMapGLBoundaryResult {
  boundaries: string[]
}

interface BMapGLEvent {
  target: any
}

// 定义 Prism 相关的选项类型
interface PrismOptions {
  topFillColor?: string
  topFillOpacity?: number
  sideFillColor?: string
  sideFillOpacity?: number
}

const initMap = () => {
  nextTick(() => {
    // 初始化地图
    const map = new (window as any).BMapGL.Map('map')
    map.setMapStyleV2({styleId: 'c1100cbde675092ba82172a63042a96a'})
    map.centerAndZoom(new (window as any).BMapGL.Point(position.latitude,position.longitude), zoom.value)
    map.enableScrollWheelZoom(true)
    map.setTilt(50)

    const bd1 = new (window as any).BMapGL.Boundary()
    /**
     * 绘制3D棱柱
     */
    bd1.get('苏州市', (rs: BMapGLBoundaryResult) => {
      const count = rs.boundaries.length
      for (let i = 0; i < count; i++) {
        const path: any[] = []
        const str = rs.boundaries[i].replace(' ', '')
        const points = str.split(';')

        for (let j = 0; j < points.length; j++) {
          const lng = points[j].split(',')[0]
          const lat = points[j].split(',')[1]
          path.push(new (window as any).BMapGL.Point(lng, lat))
        }

        // 创建3D覆盖物
        const prism = new (window as any).BMapGL.Prism(path, 5000, {
          topFillColor: '#0f1c4b',
          topFillOpacity: 0.3,
          sideFillColor: '#161690',
          sideFillOpacity: 0.9
        } as PrismOptions)

        map.addOverlay(prism)

        // 绑定鼠标事件
        const events = ['click', 'mouseover', 'mouseout']
        for (let k = 0; k < events.length; k++) {
          prism.addEventListener(events[k], (e: BMapGLEvent) => {
            switch (events[k]) {
              case 'click':
                break
              case 'mouseover':
                e.target.setTopFillColor('#5679ea')
                e.target.setTopFillOpacity(1)
                break
              case 'mouseout':
                e.target.setTopFillColor('#0f1c4b')
                e.target.setTopFillOpacity(0.5)
                break
            }
          })
        }
      }
    })

    /**
     * 绘制点
     */
    // 创建自定义覆盖物
    for (let i = 0; i < mapPoints.value.length; i++){
      const point = new (window as any).BMapGL.Point(mapPoints.value[i].latitude, mapPoints.value[i].longitude)
      const customOverlay =  new (window as any).BMapGL.CustomOverlay(createDOM, {
        point: point,
        opacity: 0.5,
        map: map,
        properties: {
          title: 'this is a title',
          size: '100'
        },
        enableDraggingMap: true
      });
      map.addOverlay(customOverlay)

      const sContent = `
        <div>
            <h4 style="margin: 0 0 5px 0; color: #ffffff; font-weight: bold; text-align: center;">
                ${mapPoints.value[i].deptName}
            </h4>
            <p style="margin: 0; line-height: 1.5; font-size: 13px; text-indent: 2em; color: #ffffff;">
                车辆数：${mapPoints.value[i].count}
            </p>
        </div>
        `;
      let opts = {
        width: 250,     // 信息窗口宽度
        height: 100,    // 信息窗口高度
        title: "企业信息" , // 信息窗口标题
        enableMessage: true,
        enableAutoPan: true,
        enableCloseOnClick: true,
        enableCloseOnClickMap: true,
        message: sContent
      }
      const infoWindow = new (window as any).BMapGL.InfoWindow(
         sContent, opts);  // 创建信息窗口对象

      // 绑定鼠标事件
      customOverlay.addEventListener('click',  (e)=> {
        map.openInfoWindow(infoWindow,point);        // 打开信息窗口


        console.log('eeee', mapPoints.value[i]);
      });
    }

  })
}
// 创建自定义覆盖物DOM
const createDOM=()=>{
  const img = document.createElement('img');
  img.style.width = '100%';
  img.style.height = '100%';
  img.src = 'https://tzsb.jscaiicloud.cn/static/visualization/visualizationMap/agent-h.png';
  img.draggable = false;
  const div = document.createElement('div');
  div.style.position = 'relative';
  div.style.width = '30px'; // 确保宽度可以自适应内容
  div.style.height = '30px'; // 确保高度可以自适应内容
  div.appendChild(img);
  return div;
}


const position = reactive<any>({latitude: 120.5, longitude: 31.20})
const zoom = ref(10)
const title = ref("")
const getData =async () => {
  await getMapCenter().then((res) => {
    if (res.code) {
      for (let item of res.data) {
        const value = JSON.parse(item.statisticalValue);
        switch (item.type) {
          case "title":
            title.value = value.data;
            break;
          case "data":
            position.latitude = value.data.latitude;
            position.longitude = value.data.longitude;
            zoom.value = value.data.zoom;
            break;
        }

      }
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    ElMessage.error(err)
  });
  ;
};
const mapPoints = ref([])
const getPoints=async ()=>{
  await getMapPoints().then(res=>{
    mapPoints.value = res.data
  },err=>{
  })
}
onMounted(async () => {
  await getData()
  await getPoints()
  initMap()

})

</script>

<style scoped lang="scss">

.centermap {
  width: 100%;
  height: 100%;
  .mapwrap {
    height: 100%;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;
  }
}


::v-deep .BMap_bubble_pop {
  background-color: rgba(55, 117, 255, 0.43) !important;
  background-size: 100% 100% !important;
  border: 0 !important;
  border-radius: 10px;
  color: #d3d6dd;
}

/*地图标题*/
::v-deep .BMap_bubble_title {
  color: #e3e3e3 !important;
  width: 100% !important;
  font-size:15px;
  font-weight:bold;
  text-align:left;
  padding-left:5px;
  padding-top:5px;
  border-bottom:1px solid gray;
  background-color:#0066b3;
}

</style>